import 'dart:io';

import 'package:flutter/material.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/launch_util.dart';
import 'package:gzmall_app/common/refresh_listview.dart';
import 'package:gzmall_app/common/setting_util.dart';
import 'package:gzmall_app/common/share_util.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'package:gzmall_app/mine/order_page.dart';
import 'package:gzmall_app/model/store.dart';
import 'package:gzmall_app/model/user.dart';
import 'package:gzmall_app/store/store_detail_page.dart';
import 'package:package_info/package_info.dart';
import "package:pull_to_refresh/pull_to_refresh.dart";
import 'package:cached_network_image/cached_network_image.dart';
import 'dart:async';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:url_launcher/url_launcher.dart';

class MineWidget extends StatefulWidget {
  Function onSelectTab;

  MineWidget({this.onSelectTab});

  @override
  MineWidgetState createState() {
    return new MineWidgetState(onSelectTab: this.onSelectTab);
  }
}

class MineWidgetState extends State<MineWidget> {
  Function onSelectTab;

  User _user = User.empty();

  double _topPadding;
  double _bottomPadding;

  RefreshListView _refreshListView;

  MineWidgetState({this.onSelectTab});

  @override
  void initState() {
    super.initState();
    _getUserInfoFromLocate(true);
  }

  @override
  Widget build(BuildContext context) {
    init();
    return new Container(
      decoration: new BoxDecoration(color: Colors.white),
      child: _createRefresh(context),
    );
  }

  void init() {
    _topPadding = MediaQuery.of(context).padding.top;
    _bottomPadding = MediaQuery.of(context).padding.bottom;
  }

  _createTitleBar() {
    return new Container(
      padding: EdgeInsets.fromLTRB(10.0, _topPadding + 10.0, 10.0, 10.0),
      color: ColorCommon.primaryColor,
      child: new Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          new Container(
            margin: const EdgeInsets.only(right: 15.0),
            child: new GestureDetector(
              child: new Image.asset(
                "images/setting.png",
                width: 20.0,
                height: 20.0,
              ),
              onTap: () {
                Navigator.of(context).pushNamed('/setting_page').then((v) {
                  _getUserInfoFromLocate(false);
                });
              },
            ),
          ),
          new GestureDetector(
            child: new Image.asset(
              "images/message.png",
              width: 20.0,
              height: 20.0,
            ),
            onTap: () {
              Navigator.of(context).pushNamed('/message_center_page').then((v) {
                _getUserInfoFromLocate(false);
              });
            },
          ),
        ],
      ),
    );
  }

  _createRefresh(BuildContext context) {
    var _iBuilder = ((BuildContext context, int mode) {
      return Container(
          color: ColorCommon.primaryColor,
          child: ClassicIndicator(
            mode: mode,
            releaseText: '松开刷新数据',
            refreshingText: '刷新中...',
            completeText: '刷新完成',
            noDataText: '没有更多的数据',
            failedText: '刷新失败',
            idleText: '拉动刷新',
            textStyle: TextStyle(color: Colors.white),
          ));
    });
    _refreshListView = RefreshListView(
      headerBuilder: _iBuilder,
      onRefresh: _onRefresh,
      headerConfig: RefreshConfig(triggerDistance: 50.0, visibleRange: 50.0),
      child: ListView(
        padding: EdgeInsets.only(top: 0.0),
        children: <Widget>[
          _createTitleBar(),
          _createPersonInfoView(),
          _createOrderView(),
          new Container(
            height: 15.0,
            color: ColorCommon.grey10,
          ),
          // _createAdvView(),
          _createServiceView(),
        ],
      ),
    );
    return _refreshListView;
  }

  void _onRefresh(bool up) {
    if (up) {
      _getUserInfoFromLocate(false);
    }
  }

  void _onOffsetChange(bool up, double offset) {}

  _createPersonInfoView() {
    return new SizedBox(
      width: MediaQuery.of(context).size.width,
      child: new Stack(
        children: <Widget>[
          new Container(
            height: 110.0,
            color: ColorCommon.primaryColor,
          ),
          new Column(
            children: <Widget>[
              new GestureDetector(
                onTap: () {
                  if (_user.authToken != null && _user.authToken.isNotEmpty) {
                    Navigator.of(context)
                        .pushNamed('/person_info_page')
                        .then((v) {
                      _getUserInfoFromLocate(false);
                    });
                  } else {
                    Navigator.of(context).pushNamed('/login_page').then((v) {
                      _getUserInfoFromLocate(false);
                    });
                  }
                },
                child: Row(
                  children: <Widget>[
                    new Container(
                      width: 56.0,
                      height: 56.0,
                      margin: const EdgeInsets.only(
                          left: 20.0, right: 15.0, top: 10.0, bottom: 15.0),
                      decoration: _user != null &&
                              _user.avatar != null &&
                              _user.avatar.isNotEmpty
                          ? new BoxDecoration(
                              borderRadius: const BorderRadius.all(
                                  Radius.circular(100.0)),
                              image: new DecorationImage(
                                image: new CachedNetworkImageProvider(
                                    _user.avatar),
                                fit: BoxFit.fill,
                              ),
                            )
                          : BoxDecoration(
                              color: Colors.grey,
                              borderRadius: const BorderRadius.all(
                                  Radius.circular(100.0)),
                            ),
                    ),
                    new Text(
                      _user != null &&
                              _user.nickname != null &&
                              _user.nickname.isNotEmpty
                          ? _user.nickname
                          : "未登录",
                      style: new TextStyle(fontSize: 20.0, color: Colors.white),
                    )
                  ],
                ),
              ),
              new Container(
                margin: const EdgeInsets.only(
                    left: 15.0, right: 15.0, bottom: 15.0),
                decoration: new BoxDecoration(
                  color: Colors.white,
                  boxShadow: [
                    new BoxShadow(
                      color: ColorCommon.grey1,
                      blurRadius: 10.0,
                    )
                  ],
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(10.0),
                      topRight: Radius.circular(10.0),
                      bottomLeft: Radius.circular(
                          _user.userMembership != null ? 0.0 : 10.0),
                      bottomRight: Radius.circular(
                          _user.userMembership != null ? 0.0 : 10.0)),
                ),
                child: new Column(
                  children: <Widget>[
                    new Padding(
                      padding: const EdgeInsets.only(top: 20.0, bottom: 20.0),
                      child: new Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: <Widget>[
                          _getCountInfoView(
                              "收藏",
                              _user != null && _user.favoriteSpusCount != null
                                  ? _user.favoriteSpusCount
                                  : 0, () {
                            Navigator.of(context).pushNamed('/collect_page');
                          }),
                          _getCountInfoView(
                              "关注",
                              _user != null
                                  ? ((_user.favoriteBrandsCount != null
                                          ? _user.favoriteBrandsCount
                                          : 0) +
                                      (_user.favoriteShopsCount != null
                                          ? _user.favoriteShopsCount
                                          : 0))
                                  : 0, () {
                            Navigator.of(context).pushNamed('/follow_page');
                          }),
                          _getCountInfoView(
                              "足迹",
                              _user != null && _user.spuTracksCount != null
                                  ? _user.spuTracksCount
                                  : 0, () {
                            Navigator.of(context).pushNamed('/footprint_page');
                          }),
                        ],
                      ),
                    ),
                    // _user.userMembership != null
                    //     ? new Container(
                    //         padding: const EdgeInsets.only(
                    //             left: 15.0,
                    //             right: 10.0,
                    //             top: 10.0,
                    //             bottom: 10.0),
                    //         decoration: new BoxDecoration(
                    //             borderRadius: BorderRadius.only(
                    //                 bottomLeft: Radius.circular(10.0),
                    //                 bottomRight: Radius.circular(10.0)),
                    //             gradient: const LinearGradient(colors: [
                    //               ColorCommon.yellow1,
                    //               ColorCommon.yellow2,
                    //               ColorCommon.yellow3,
                    //             ])),
                    //         child: new Row(
                    //           children: <Widget>[
                    //             new Expanded(
                    //               child: new Row(
                    //                 children: <Widget>[
                    //                   _user?.userMembership?.avatar != null &&
                    //                           _user.userMembership.avatar
                    //                               .isNotEmpty
                    //                       ? CachedNetworkImage(
                    //                           imageUrl:
                    //                               _user.userMembership.avatar,
                    //                           width: 30.0,
                    //                           height: 30.0,
                    //                           fit: BoxFit.fill,
                    //                         )
                    //                       : Container(
                    //                           width: 30.0,
                    //                           height: 30.0,
                    //                           color: Colors.grey,
                    //                         ),
                    //                   new Container(
                    //                     margin:
                    //                         const EdgeInsets.only(left: 10.0),
                    //                     child: new Text(
                    //                       _user.userMembership.name ?? "",
                    //                       style: new TextStyle(
                    //                           fontSize: 15.0,
                    //                           color: Colors.white),
                    //                     ),
                    //                   ),
                    //                 ],
                    //               ),
                    //             ),
                    //             // new Container(
                    //             //   margin: const EdgeInsets.only(right: 4.0),
                    //             //   child: new Text(
                    //             //     "点击查看特权",
                    //             //     style: new TextStyle(
                    //             //         fontSize: 15.0, color: Colors.white),
                    //             //   ),
                    //             // ),
                    //             // new Image.asset(
                    //             //   "images/right_arrow.png",
                    //             //   width: 10.0,
                    //             //   height: 10.0,
                    //             // ),
                    //           ],
                    //         ),
                    //       )
                    //     : Container(),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  _getCountInfoView(String text, int count, Function onTap) {
    return InkWell(
        onTap: onTap,
        child: Column(
          children: <Widget>[
            new Text(
              count.toString(),
              style: new TextStyle(fontSize: 25.0, color: ColorCommon.black3),
            ),
            new Padding(
              padding: const EdgeInsets.only(top: 10.0),
              child: new Text(
                text,
                style: new TextStyle(fontSize: 15.0, color: ColorCommon.grey3),
              ),
            ),
          ],
        ));
  }

  _createOrderView() {
    return new Container(
      padding: const EdgeInsets.only(left: 15.0, right: 15.0, bottom: 10.0),
      child: new Column(
        children: <Widget>[
          new Container(
            margin: const EdgeInsets.only(bottom: 15.0),
            child: new Row(
              children: <Widget>[
                new Expanded(
                  child: new Text(
                    "我的订单",
                    style: new TextStyle(fontSize: 18.0),
                  ),
                ),
                new Padding(
                  padding: const EdgeInsets.only(right: 4.0),
                  child: new GestureDetector(
                    onTap: () {
                      Navigator.of(context).pushNamed('/order_page').then((v) {
                        _getUserInfoFromLocate(false);
                      });
                    },
                    child: new Text(
                      "查看全部",
                      style: new TextStyle(
                          fontSize: 14.0, color: ColorCommon.grey4),
                    ),
                  ),
                ),
                new Image.asset(
                  "images/right_arrow.png",
                  width: 10.0,
                  height: 10.0,
                ),
              ],
            ),
          ),
          new Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              _getOrderStateView(0),
              _getOrderStateView(1),
              _getOrderStateView(2),
              _getOrderStateView(3),
              _getOrderStateView(4),
            ],
          ),
        ],
      ),
    );
  }

  _getOrderStateView(int state) {
    String stateStr, stateIcon;
    switch (state) {
      case 0:
        stateStr = "待付款";
        stateIcon = "images/order_state_pending.png";
        break;
      case 1:
        stateStr = "待发货";
        stateIcon = "images/order_state_dispatch.png";
        break;
      case 2:
        stateStr = "待收货";
        stateIcon = "images/order_state_receive.png";
        break;
      case 3:
        stateStr = "评价";
        stateIcon = "images/order_state_evaluation.png";
        break;
      case 4:
        stateStr = "退款退货";
        stateIcon = "images/order_state_return.png";
        break;
    }
    return new GestureDetector(
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(builder: (_) {
          return OrderPage(
            curIndex: (state + 1),
          );
        })).then((v) {
          _getUserInfoFromLocate(false);
        });
      },
      child: new Column(
        children: <Widget>[
          new Image.asset(
            stateIcon,
            width: 25.0,
            height: 25.0,
          ),
          new Container(
            margin: const EdgeInsets.only(top: 8.0),
            child: new Text(
              stateStr,
              style: new TextStyle(fontSize: 14.0, color: ColorCommon.black2),
            ),
          ),
        ],
      ),
    );
  }

  _createAdvView() {
    return new Container(
      child: new CachedNetworkImage(
        imageUrl: "http://via.placeholder.com/350x150",
        height: 100.0,
        fit: BoxFit.fill,
      ),
    );
  }

  _createServiceView() {
    return new Container(
      padding: const EdgeInsets.only(
          left: 15.0, right: 15.0, top: 15.0, bottom: 15.0),
      child: new Column(
        children: <Widget>[
          new Container(
            margin: const EdgeInsets.only(bottom: 15.0),
            child: new Row(
              children: <Widget>[
                new Expanded(
                  child: new Text(
                    "我的服务",
                    style: new TextStyle(fontSize: 18.0),
                  ),
                ),
                // new Padding(
                //   padding: const EdgeInsets.only(right: 4.0),
                //   child: new Text(
                //     "查看全部",
                //     style:
                //         new TextStyle(fontSize: 14.0, color: ColorCommon.grey4),
                //   ),
                // ),
                // new Image.asset(
                //   "images/right_arrow.png",
                //   width: 10.0,
                //   height: 10.0,
                // ),
              ],
            ),
          ),
          new Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              _getServiceView("我要开店", "images/service_create_shop.png", () {
                _openStore();
              }),
              _getServiceView("领券中心", "images/service_ticket_center.png", () {
                Navigator.of(context)
                    .pushNamed('/coupon_center_page')
                    .then((v) {
                  _getUserInfoFromLocate(false);
                });
              }),
              _getServiceView("优惠券", "images/service_coupon.png", () {
                Navigator.of(context).pushNamed('/coupon_page').then((v) {
                  _getUserInfoFromLocate(false);
                });
              }),
              _getServiceView("充值返现", "images/service_topup.jpeg", () {
                Navigator.of(context).pushNamed('/topup_page');
              }),
            ],
          ),
          new Padding(
            padding: const EdgeInsets.only(top: 20.0),
            child: new Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                _getServiceView("帮助与客服", "images/service_customer.png", () {
                  if (SettingUtil.tel != null && SettingUtil.tel != '') {
                    _makePhoneCall('tel:${SettingUtil.tel}');
                  } else {
                    ToastUtil.showMessageToast('商家电话错误');
                  }
                }),
                LaunchUtil.isInstallWeixin && !SettingUtil.isAppStoreAudit()
                    ? _getServiceView("分享给好友", "images/service_share.png", () {
                        if (_user.shareUrl != null &&
                            _user.shareUrl.isNotEmpty &&
                            _user.shareAvatar != null &&
                            _user.shareAvatar.isNotEmpty) {
                          ShareUtil.showShareSelect(
                              context,
                              _user.shareUrl,
                              _user.shareTitle,
                              _user.shareContent,
                              _user.shareAvatar,
                              _user.shareTitle);
                        } else {
                          PackageInfo.fromPlatform()
                              .then((PackageInfo packageInfo) {
                            ShareUtil.showShareSelect(
                                context,
                                Platform.isIOS
                                    ? SettingUtil.iDLDUrl
                                    : SettingUtil.aDLDUrl,
                                packageInfo?.appName,
                                "",
                                "assets://images/ic_launcher.png",
                                packageInfo?.appName);
                          });
                        }
                      })
                    : Expanded(
                        child: new SizedBox(),
                      ),
                // new Expanded(
                //   child: new SizedBox(),
                // ),
                new Expanded(
                  child: new SizedBox(),
                ),
                new Expanded(
                  child: new SizedBox(),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  _getServiceView(String name, String iconPath, GestureTapCallback onTap) {
    return new Expanded(
      child: new GestureDetector(
        onTap: onTap,
        child: new Column(
          children: <Widget>[
            new Image.asset(
              iconPath,
              width: 40.0,
              height: 40.0,
            ),
            new Container(
              margin: const EdgeInsets.only(top: 8.0),
              child: new Text(
                name,
                style: new TextStyle(fontSize: 14.0, color: ColorCommon.black1),
              ),
            ),
          ],
        ),
      ),
    );
  }

  _getUserInfoFromLocate(bool isFirst) async {
    await _user.getUserInfo();
    if (_user.id > 0 && _user.authToken != null && _user.authToken.isNotEmpty) {
      _getUserInfoFromNet(_user.id, isFirst);
    } else {
      if (!mounted) return;
      if (!isFirst && _refreshListView != null) {
        _refreshListView.refreshCompleted(true);
      }
      setState(() {
        _user = User.empty();
      });
    }
  }

  _getUserInfoFromNet(int id, bool isFirst) {
    NetUtil.get(
        context,
        Api.users + id.toString(),
        (data, message) {
          if (!mounted) return;
          if (!isFirst && _refreshListView != null) {
            _refreshListView.refreshCompleted(true);
          }
          setState(() {
            String _authToken = _user.authToken;
            _user = User.fromJson(data);
            _user.authToken = _authToken;
            User.saveUserInfo(_user);
          });
        },
        isInterceptError: false,
        errorCallBack: (e) {
          if (!mounted) return;
          if (!isFirst && _refreshListView != null) {
            _refreshListView.refreshCompleted(true);
          }
        });
  }

  _openStore() {
    NetUtil.post(context, Api.openShops, (data, message) {
      if (data["open"]) {
        Store store = Store(data["id"], '', '', '', '', '', '', 0.0, 0.0, '',
            '', [], false, '', '', '', '');
        Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
          return new StoreDetailPage(store: store);
        }));
      } else {
        Navigator.of(context).pushNamed('/open_store_page');
      }
    }, isShowLoading: true);
  }

  Future<void> _makePhoneCall(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      ToastUtil.showMessageToast('无法拨打电话');
    }
  }
}
